<template>
  <div ref="codeEditBox" class="codeEditBox"></div>
</template>

<script lang="ts">
import { defineComponent, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { defineMonacoTheme } from './monacmDefineThemes'
import { editorProps } from './monacoEditorType'
import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker'
import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker'
import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker'
import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker'
import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker'
import * as monaco from 'monaco-editor'
import './snippets/index'

export default defineComponent({
  name: 'monacoEditor',
  props: editorProps,
  emits: ['update:modelValue', 'change', 'editor-mounted', 'key-shift-enter'],
  setup(props, { emit, expose }) {
    self.MonacoEnvironment = {
      getWorker(_: string, label: string) {
        if (label === 'json') {
          return new jsonWorker()
        }
        if (['css', 'scss', 'less'].includes(label)) {
          return new cssWorker()
        }
        if (['html', 'handlebars', 'razor'].includes(label)) {
          return new htmlWorker()
        }
        if (['typescript', 'javascript'].includes(label)) {
          return new tsWorker()
        }
        return new EditorWorker()
      }
    }

    let editor: monaco.editor.IStandaloneCodeEditor
    const codeEditBox = ref()
    let prevHeight = ref(0)
    const updateEditorHeight = () => {
      const editorElement = editor.getDomNode()

      if (!editorElement) {
        return
      }

      const padding = 0

      const lineHeight = editor.getOption(monaco.editor.EditorOption.lineHeight)
      const lineCount = editor.getModel()?.getLineCount() || 1
      const height =
        editor.getTopForLineNumber(lineCount + 1) + lineHeight + padding

      if (prevHeight.value !== height) {
        prevHeight.value = height
        editorElement.style.height = `${height}px`
        editor.layout()
      }
    }
    //shift-enter不换行
    const noWrap = () => {
      editor.updateOptions({ wordWrap: 'off' })
      emit('key-shift-enter')
    }
    const init = async () => {
      monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
        noSemanticValidation: true,
        noSyntaxValidation: false
      })
      monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
        target: monaco.languages.typescript.ScriptTarget.ES2020,
        allowNonTsExtensions: true
      })
      defineMonacoTheme()

      editor = monaco.editor.create(codeEditBox.value, {
        value: props.modelValue,
        language: props.language,
        theme: props.theme,
        ...props.options
      })

      // 监听值的变化
      editor.onDidChangeModelContent(() => {
        const value = editor.getValue() //给父组件实时返回最新文本
        emit('update:modelValue', value)
        emit('change', value)
      })

      emit('editor-mounted', editor)

      //动态更新高度
      editor.onDidChangeModelDecorations(() => {
        updateEditorHeight() // typing
        // requestAnimationFrame(updateEditorHeight) // folding
        editor.addAction({
          id: 'noRun',
          label: 'noRun',
          keybindings: [
            monaco.KeyMod.chord(monaco.KeyMod.Shift | monaco.KeyCode.Enter, 0)
          ],
          run: noWrap
        })
      })
    }

    watch(
      () => props.modelValue,
      (newValue) => {
        if (editor) {
          const value = editor.getValue()
          if (newValue !== value) {
            editor.setValue(newValue)
          }
        }
      }
    )

    watch(
      () => props.options,
      (newValue) => {
        editor.updateOptions(newValue)
      },
      { deep: true }
    )

    watch(
      () => props.language,
      async (newValue) => {
        monaco.editor.setModelLanguage(editor.getModel()!, newValue)
        // console.log(props.language)
      }
    )

    onBeforeUnmount(() => {
      editor.dispose()
    })

    onMounted(async () => {
      init()
      // if (props.language && languages[props.language]) {
      //   const registerSnippets = await languages[props.language]()
      //   registerSnippets.default(monaco)
      // }
    })
    //重新渲染高度
    const render = () => {
      const editorElement = editor.getDomNode()
      editorElement!.style.height = `${prevHeight.value}px`
      editor.layout()
    }
    expose({
      render
    })
    return { codeEditBox }
  }
})
</script>

<style lang="scss" scoped>
.codeEditBox {
  width: v-bind(width);
  // height: v-bind(height);
  // height: 100%;
}
</style>
